package com.neko.Thread_Learning.t16_No_synchronized_Demo;

/**
 * 不安全地 取钱
 * 2个人去银行取钱，账户余额出错
 * */
public class UnSafeBank {
    public static void main(String[] args) {
        // 账户
        Account account = new Account("结婚资金", 100);

        Drawing you = new Drawing("you", account, 50);
        Drawing girlFriend = new Drawing("girlFriend", account, 100);

        you.start();
        girlFriend.start();

    }
}

// 账户
class Account {
    String name;
    int money;

    public Account(String name, int money) {
        this.name = name;
        this.money = money;
    }
}

// 银行：模拟【取款】
class Drawing extends Thread {

    Account account; // 账户
    int drawingMoney; // 取走的钱
    int nowMoney; // 剩余的钱

    public Drawing(String name, Account account, int drawingMoney) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {

        /**
         *  synchronized Block 可以锁 任何对象
         *  -----------
         *  synchronized(Object) 一定是锁的是【变化的 Object】
          */

//        synchronized (account) {
            // 判断：有没有钱
            if (account.money - drawingMoney < 0) {
                System.out.println(Thread.currentThread().getName() + " 钱不够");
                return;
            }

            // 模拟延时，以便于 2个Thread 都进入 run阶段
            // 使用 Sleep 放大 问题发生性
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 卡内余额 = 余额 - 取钱
            account.money = account.money - drawingMoney;

            // 你手里的钱
            nowMoney = nowMoney + drawingMoney;

            System.out.println(account.name + " 余额为：" + account.money);

            // this.getName() == Thread.currentThread().getName()
            System.out.println(this.getName() + "手里的钱 = " + nowMoney);
//        }


    }
}